package servidor;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import dados.Stock;

public class LigacaoActualizacao extends Thread {

	private Socket socket;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private ArrayList<Stock> stocks;
	private Servidor servidor;


	public LigacaoActualizacao(Servidor servidor, Socket socket) throws IOException {
		this.servidor = servidor;
		this.socket = socket;

		OutputStream os = socket.getOutputStream();
		out = new ObjectOutputStream(os);
		InputStream is = socket.getInputStream();
		in = new ObjectInputStream(is);
	}

	@Override
	public void run() {
		setName("Thread LigacaoActualizacao - Servidor");
		try {
			while (true) {
				stocks = servidor.recolherStocks();
				System.out.println("ACTUALIZAR PARA O CLIENTE...");
				out.flush();
				out.reset();
				out.writeObject(stocks);
				Object echo = in.readObject();
				if(echo != null && echo instanceof String){
					String eco = (String) echo;
					System.out.println("Eco: " + eco);
				}
			}
		} catch (IOException e) {
			System.out.println("Servidor(LigacaoActualizacao) - Terminado...");
		} catch (InterruptedException e) {
			System.out.println("Thread Interrompida!!!" + e);
		} catch (ClassNotFoundException e) {
			System.out.println("Class Not Found " + e);
		} finally {
			System.out.println("Servidor(LigacaoActualizacao) - a fechar...");
			try {
				socket.close();
			} catch (IOException e) {
				System.out.println("IOException ao fechar socket " + e);
			}
		}
	}
}
